package com.agileai.bpm.controller.emulation;

import java.util.ArrayList;
import java.util.List;

import com.agileai.bpm.bizmoduler.emulation.WfEmulationManage;
import com.agileai.bpm.bizmoduler.emulation.WfOwnDraftTaskManage;
import com.agileai.bpm.domain.define.Process;
import com.agileai.bpm.service.define.DefineService;
import com.agileai.bpm.service.running.RunningException;
import com.agileai.bpm.webservice.BPMService;
import com.agileai.bpm.webservice.BizAttribute;
import com.agileai.bpm.webservice.LaunchWorkItem;
import com.agileai.bpm.webservice.SubmitWorkItem;
import com.agileai.common.KeyGenerator;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.StandardEditHandler;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.RedirectRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.DateUtil;
import com.agileai.util.ListUtil;
import com.agileai.util.StringUtil;

public class WfEmulationManageEditHandler extends StandardEditHandler{
	public WfEmulationManageEditHandler(){
		super();
		this.listHandlerClass = WfEmulationManageListHandler.class;
		this.serviceId = buildServiceId(WfEmulationManage.class);
	}
	
	@SuppressWarnings("rawtypes")
	public ViewRenderer prepareDisplay(DataParam param){
		this.setAttributes(param);
		List bizDataList = (List)getAttribute("bizDataList");
		String recordId = param.get("WFE_ID");
		String processId = param.get("WFP_ID");
		String bizId = param.get("BizId");
		String invokeFrom = param.get("invokeFrom");
		if (!StringUtil.isNullOrEmpty(recordId)){
			this.setAttribute("firstEdit", false);
		}else{
			this.setAttribute("firstEdit", true);
		}
		if("BPM".equals(invokeFrom)){
			recordId=bizId;
			setAttribute("showSelectBtn", false);
			DataParam queryParam = new DataParam();
			queryParam.put("WWD_ID", param.get("WWD_ID"));
			WfOwnDraftTaskManage wfOwnDraftTaskManage = (WfOwnDraftTaskManage)this.lookupService(WfOwnDraftTaskManage.class);
			DataRow row = wfOwnDraftTaskManage.getRecord(queryParam);
			processId=row.getString("WFP_ID");
		}
		if (StringUtil.isNotNullNotEmpty(recordId) && bizDataList == null){
			DataParam queryParam = new DataParam("WFE_ID",recordId);
			DataRow row = getService().getRecord(queryParam);
			if (row != null){
				this.setAttributes(row);
				String content = row.getString("WFE_CONTENT");
				if (StringUtil.isNotNullNotEmpty(content)){
					bizDataList = ListUtil.toDataSet(content);
				}
			}
		}
		
		if (bizDataList == null){
			bizDataList = new ArrayList();
		}
		
		if (!StringUtil.isNullOrEmpty(processId)){
			DefineService defineService = (DefineService)this.lookupService("defineService");
			Process process = defineService.loadProcess(processId);
			this.setAttribute("WFP_NAME",process.getName());
		}
		
		setAttribute("bizDataList",bizDataList);
		setAttribute("bizDataSize",bizDataList.size());
		return new LocalRenderer(getPage());
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ViewRenderer doAddBizDataAction(DataParam param){
		this.setAttributes(param);
		List<DataRow> bizDataList = new ArrayList();
		int bizDataSize = param.getInt("bizDataSize");
		for (int i=0;i < bizDataSize;i++){
			String bizDataName = param.get("bizDataName_"+i);
			String bizDataCode = param.get("bizDataCode_"+i);
			String bizDataValue = param.get("bizDataValue_"+i);
			String isVarialbe = param.get("isVarialbe_"+i);
			DataRow row = new DataRow();
			row.put("bizDataName", bizDataName);
			row.put("bizDataCode", bizDataCode);
			row.put("bizDataValue", bizDataValue);
			row.put("isVarialbe",isVarialbe);
			bizDataList.add(row);
		}
		bizDataList.add(new DataRow());
		setAttribute("bizDataList", bizDataList);
		return prepareDisplay(param);
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ViewRenderer doDelBizDataAction(DataParam param){
		this.setAttributes(param);
		int bizDataIndex = param.getInt("bizDataIndex");
		List bizDataList = new ArrayList();
		int bizDataSize = param.getInt("bizDataSize");
		for (int i=0;i < bizDataSize;i++){
			if (i == bizDataIndex)continue;
			String bizDataName = param.get("bizDataName_"+i);
			String bizDataCode = param.get("bizDataCode_"+i);
			String bizDataValue = param.get("bizDataValue_"+i);
			DataRow row = new DataRow();
			row.put("bizDataName", bizDataName);
			row.put("bizDataCode", bizDataCode);
			row.put("bizDataValue", bizDataValue);
			bizDataList.add(row);
		}
		setAttribute("bizDataList", bizDataList);
		return prepareDisplay(param);
	}
	
	public ViewRenderer doSubmitAction(DataParam param) throws RunningException{
		String responseText = null;
		ProcessHelper processHelper = ProcessHelper.instance();
		int bizDataSize = param.getInt("bizDataSize");
		
		String processId = param.get("WFP_ID");
		String processInstId = param.get("WFIP_ID");
		String activityCode = param.get("WFA_CODE");
		
		BPMService bpmService = processHelper.getBPMService();
		
		User user = (User)getUser();
		
		String recordId = param.get("WFE_ID");
		
		List<BizAttribute> attributeList = new ArrayList<BizAttribute>();
		List<DataRow> bizDataList = new ArrayList<DataRow>();
		for (int i=0;i < bizDataSize;i++){
			String bizDataName = param.get("bizDataName_"+i);
			String bizDataCode = param.get("bizDataCode_"+i);
			String bizDataValue = param.get("bizDataValue_"+i);
			
			DataRow row = new DataRow();
			row.put("bizDataName", "发起——"+bizDataName);
			row.put("bizDataCode", bizDataCode);
			row.put("bizDataValue", bizDataValue);
			
			BizAttribute attribute = new BizAttribute();
			attribute.setCode(bizDataCode);
			attribute.setValue(bizDataValue);
			attributeList.add(attribute);
			bizDataList.add(row);
		}
		
		String bizDataXML = ListUtil.toXML(bizDataList);
		WfEmulationManage wfEmulationManage = getService();
		
		if (StringUtil.isNullOrEmpty(recordId)){
			KeyGenerator keyGenerator = KeyGenerator.instance();
			recordId = keyGenerator.genKey();
			param.put("WFE_ID",recordId);
			param.put("WFE_CONTENT",bizDataXML);
			param.put("WFE_CREATERID",user.getUserId());
			param.put("WFE_CREATERNAME",user.getUserName());
			param.put("WFE_CREATETIME",DateUtil.getDateByType(DateUtil.YYMMDDHHMISS_HORIZONTAL));
			param.put("WFE_STATUS","Running");
			wfEmulationManage.createRecord(param,recordId);			
		}else{
			param.put("WFE_ID",recordId);
			param.put("WFE_CONTENT",bizDataXML);
			param.put("WFE_EDITERID",user.getUserId());
			param.put("WFE_EDITERNAME",user.getUserName());
			param.put("WFE_UPDATETIME",DateUtil.getDateByType(DateUtil.YYMMDDHHMISS_HORIZONTAL));
			param.put("WFE_STATUS","Running");
			wfEmulationManage.updateRecord(param);
		}
		
		if (StringUtil.isNullOrEmpty(processInstId)){
			LaunchWorkItem launchWorkItem = processHelper.createLaunchWorkItem(processId);
			launchWorkItem.getAttributeList().addAll(attributeList);
			
			String wfeTitle = param.get("WFE_TITLE");
			launchWorkItem.setTitle(wfeTitle);
			launchWorkItem.setBizRecordId(recordId);
			launchWorkItem.setUserCode(user.getUserCode());
			
			boolean skipFirstNode = "true".equals(param.get("SKIP_FIRST_NODE"));
			bpmService.launchProcess(launchWorkItem,skipFirstNode);
		}else{
			SubmitWorkItem processWorkItem = processHelper.createSubmitWorkItem(processId, processInstId, activityCode);
			attributeList = processWorkItem.getAttributeList();
			processWorkItem.setUserCode(user.getUserCode());
			processWorkItem.getAttributeList().addAll(attributeList);
			
			bpmService.submitProcess(processWorkItem);
		}
		responseText = SUCCESS;
		return new AjaxRenderer(responseText);
	}
	@PageAction
	public ViewRenderer save(DataParam param){
		String responseText = null;
		String recordId = param.get("WFE_ID");
		String processId = param.get("WFP_ID");
		String wfeTitle = param.get("WFE_TITLE");
		int bizDataSize = param.getInt("bizDataSize");
		User user = (User)getUser();
		WfEmulationManage wfEmulationManage = getService();
		List<BizAttribute> attributeList = new ArrayList<BizAttribute>();
		List<DataRow> bizDataList = new ArrayList<DataRow>();
		for (int i=0;i < bizDataSize;i++){
			String bizDataName = param.get("bizDataName_"+i);
			String bizDataCode = param.get("bizDataCode_"+i);
			String bizDataValue = param.get("bizDataValue_"+i);
			
			DataRow row = new DataRow();
			row.put("bizDataName", bizDataName);
			row.put("bizDataCode", bizDataCode);
			row.put("bizDataValue", bizDataValue);
			
			BizAttribute attribute = new BizAttribute();
			attribute.setCode(bizDataCode);
			attribute.setValue(bizDataValue);
			attributeList.add(attribute);
			bizDataList.add(row);
		}
		String bizDataXML = ListUtil.toXML(bizDataList);
		if (StringUtil.isNullOrEmpty(recordId)){
			KeyGenerator keyGenerator = KeyGenerator.instance();
			recordId = keyGenerator.genKey();
			param.put("WFE_ID",recordId);
			param.put("WFE_CONTENT",bizDataXML);
			param.put("WFE_CREATERID",user.getUserId());
			param.put("WFE_CREATERNAME",user.getUserName());
			param.put("WFE_CREATETIME",DateUtil.getDateByType(DateUtil.YYMMDDHHMISS_HORIZONTAL));
			param.put("WFE_STATUS","Init");
			wfEmulationManage.createRecord(param,recordId);	
			DataParam draftParam = new DataParam();
			draftParam.put("WFP_ID", processId);
			draftParam.put("WWD_BIZ_ID", recordId);
			draftParam.put("WWD_BIZ_TITLE", wfeTitle);
			draftParam.put("WWD_CREATER", user.getUserId());
			draftParam.put("WWD_CREATE_TIME", DateUtil.getDateByType(DateUtil.YYMMDDHHMISS_HORIZONTAL));
			wfEmulationManage.createDraftRecord(draftParam,recordId);
		}else{
			param.put("WFE_ID",recordId);
			param.put("WFE_CONTENT",bizDataXML);
			param.put("WFE_EDITERID",user.getUserId());
			param.put("WFE_EDITERNAME",user.getUserName());
			param.put("WFE_UPDATETIME",DateUtil.getDateByType(DateUtil.YYMMDDHHMISS_HORIZONTAL));
			param.put("WFE_STATUS","Init");
			wfEmulationManage.updateRecord(param);
		}
		responseText = "success";
		return new AjaxRenderer(responseText);
	}
	
	public ViewRenderer doBackAction(DataParam param){
		return new RedirectRenderer(getHandlerURL(listHandlerClass));
	}	
	
	protected WfEmulationManage getService() {
		return (WfEmulationManage)this.lookupService(this.getServiceId());
	}
}